/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * HistorialNeumatico.java
 *
 * Created on 06-ago-2012, 21:52:28
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.Vehiculos;
import com.camachosanchez.controler.jpa.NeumaticosJpaController;
import com.camachosanchez.gui.table.RenderizadorBlanco;
import com.camachosanchez.gui.table.TableSorter;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.GUIUtil;
import com.camachosanchez.util.JPAUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.coderazzi.filters.gui.TableFilterHeader;

/**
 *
 * @author Rolando
 */
public class HistorialNeumatico extends javax.swing.JDialog {

    private int idNeumatico;
    private SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy");
    private DefaultTableModel modeloReencuaches;
    private DefaultTableModel modeloCambios;
    private TableFilterHeader filterHeaderReencuaches;
    private TableFilterHeader filterHeaderCambios;

    /** Creates new form HistorialNeumatico */
    public HistorialNeumatico(java.awt.Frame parent, boolean modal, int idNeumatico, String codigo) {
        super(parent, modal);
        initComponents();
        this.setTitle(".:: Historial de neumático " + codigo + " ::.");
        modeloReencuaches = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int col) {
                return false;
            }
        };
        Object[] columnsR = new Object[]{"", "ENVÍO", "DISTRIBUIDOR", "Nº FACTURA", "RECEPCIÓN", "NUEVA BANDA", "NUEVO PISO", "GUÍA DE REMISIÓN", "PRECIO", "OBSERVACIONES"};
        modeloReencuaches.setColumnIdentifiers(columnsR);
        modeloCambios = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int col) {
                return false;
            }
        };
        Object[] columnsC = new Object[]{"", "FECHA", "VEHÍCULO", "TALLER", "KILOMETRAJE", "TIPO", "POSICIÓN", "OBSERVACIÓN"};
        modeloCambios.setColumnIdentifiers(columnsC);
        this.idNeumatico = idNeumatico;
        filterHeaderReencuaches = new TableFilterHeader();
        filterHeaderCambios = new TableFilterHeader();
        TableSorter tableSorterReencuaches = new TableSorter(modeloReencuaches, tblReencauches.getTableHeader());
        TableSorter tableSorterCambios = new TableSorter(modeloCambios, tblCambios.getTableHeader());
        tblReencauches.setModel(tableSorterReencuaches);
        tblCambios.setModel(tableSorterCambios);
        filterHeaderReencuaches.setTable(tblReencauches);
        filterHeaderCambios.setTable(tblCambios);
        RenderizadorBlanco render1 = new RenderizadorBlanco(tblCambios.getTableHeader().getDefaultRenderer());
        RenderizadorBlanco render2 = new RenderizadorBlanco(tblCambios.getTableHeader().getDefaultRenderer());
        tblCambios.setDefaultRenderer(Object.class, render1);
        tblReencauches.setDefaultRenderer(Object.class, render2);
        tblCambios.getTableHeader().setReorderingAllowed(false);
        tblReencauches.getTableHeader().setReorderingAllowed(false);
        this.setSize(700, 400);
        this.setLocationRelativeTo(null);
        llenarTablaReencauche();
        llenarTablaMontajes();
        GUIUtil.addEscapeKey(this);
    }

    private void llenarTablaReencauche() {
        EntityManagerFactory emf;
        emf = JPAUtil.getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        Query q = em.createQuery("SELECT C.fechaEnvio, C.idDistribuidorNeumaticos.nombre, C.numFactura, C.fechaRecepcion,"
                + " R.idNuevoTipoBanda.nombre, R.idNuevoTipoPiso.nombre, C.numGuiaRemision, R.precio, R.observacionesRecepcion"
                + " FROM DetalleControlReencauche R JOIN R.idControlReencauche C"
                + " WHERE R.idNeumatico.id = :idNeumatico ORDER BY C.fechaEnvio");
        q.setParameter("idNeumatico", this.idNeumatico);
        Iterator results = q.getResultList().iterator();
        Date fechaEnvio, fechaRec;
        Object[] fila;
        while (results.hasNext()) {
            Object[] tupla = (Object[]) results.next();
            fila = new Object[10];
            if (tupla[0] != null) {
                fechaEnvio = (Date) tupla[0];
                fila[1] = formatoFecha.format(fechaEnvio);
            }
            fila[2] = tupla[1];
            fila[3] = tupla[2];
            if (tupla[3] != null) {
                fechaRec = (Date) tupla[3];
                fila[4] = formatoFecha.format(fechaRec);
            }
            fila[5] = tupla[4];
            fila[6] = tupla[5];
            fila[7] = tupla[6];
            fila[8] = tupla[7];
            fila[9] = tupla[8];
            modeloReencuaches.addRow(fila);
        }
        GUIUtil.SetAnchoColumnas(tblReencauches);
    }

    private void llenarTablaMontajes() {
        EntityManagerFactory emf;
        emf = JPAUtil.getEntityManagerFactory();
        EntityManager em = emf.createEntityManager();
        Query q = em.createQuery("SELECT C.fecha, C.idVehiculo.placa, C.idTaller.nombre, C.kilometraie,"
                + " D.tipo, D.posicion, D.observacion"
                + " FROM DetalleControlCambioNeumatico D"
                + " JOIN D.idControlCambioNeumatico C"
                + " WHERE D.idNeumatico.id = :idNeumatico ORDER BY C.fecha");
        q.setParameter("idNeumatico", this.idNeumatico);
        Iterator results = q.getResultList().iterator();
        Date fecha;
        Object[] fila;
        while (results.hasNext()) {
            Object[] tupla = (Object[]) results.next();
            fila = new Object[8];
            if (tupla[0] != null) {
                fecha = (Date) tupla[0];
                fila[1] = formatoFecha.format(fecha);
            }
            fila[2] = tupla[1];
            fila[3] = tupla[2];
            fila[4] = tupla[3];
            int tipo = Integer.parseInt(tupla[4].toString());
            switch (tipo) {
                case -1:
                    fila[5] = "Desmontaje";
                    break;
//                case 0: fila[4] = "Neutro";
//                         break;
                case 1:
                    fila[5] = "Montaje";
                    break;
                default:
                    fila[5] = "";
                    break;
            }
            if (tupla[5].toString().compareTo("-1") == 0) {
                tupla[5] = "R";
            }
            fila[6] = tupla[5];
            fila[7] = tupla[6];
            if (tipo != 0) {
                modeloCambios.addRow(fila);
            }
        }
        GUIUtil.SetAnchoColumnas(tblCambios);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jPanel3 = new javax.swing.JPanel();
        btnVerUbicacion = new javax.swing.JButton();
        btnImprimir = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblCambios = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblReencauches = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Historial de neumático ::.");
        setResizable(false);

        jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setOpaque(false);

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        btnVerUbicacion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_ubicacion.png"))); // NOI18N
        btnVerUbicacion.setToolTipText("Ver ubicación");
        btnVerUbicacion.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnVerUbicacion.setFocusable(false);
        btnVerUbicacion.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnVerUbicacion.setMaximumSize(new java.awt.Dimension(22, 22));
        btnVerUbicacion.setMinimumSize(new java.awt.Dimension(22, 22));
        btnVerUbicacion.setPreferredSize(new java.awt.Dimension(22, 22));
        btnVerUbicacion.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnVerUbicacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerUbicacionActionPerformed(evt);
            }
        });
        jPanel3.add(btnVerUbicacion);

        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_print.png"))); // NOI18N
        btnImprimir.setToolTipText("Imprirmir");
        btnImprimir.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnImprimir.setFocusable(false);
        btnImprimir.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnImprimir.setMaximumSize(new java.awt.Dimension(22, 22));
        btnImprimir.setMinimumSize(new java.awt.Dimension(22, 22));
        btnImprimir.setPreferredSize(new java.awt.Dimension(22, 22));
        btnImprimir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });
        jPanel3.add(btnImprimir);

        jToolBar1.add(jPanel3);

        getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        jPanel4.setLayout(new java.awt.BorderLayout());

        jTabbedPane1.setBackground(new java.awt.Color(188, 211, 226));
        jTabbedPane1.setOpaque(true);

        jPanel1.setBackground(new java.awt.Color(188, 211, 226));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("MONTAJES Y DESMONTAJES");
        jLabel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 1, 5, 1));
        jPanel1.add(jLabel1, java.awt.BorderLayout.PAGE_START);

        jScrollPane1.setBorder(null);

        tblCambios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblCambios.setRowHeight(22);
        tblCambios.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tblCambios);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab("HISTORIAL DE CAMBIOS", jPanel1);

        jPanel2.setBackground(new java.awt.Color(188, 211, 226));
        jPanel2.setLayout(new java.awt.BorderLayout());

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("ENVÍOS Y RECEPCIONES DE REENCAUCHE");
        jLabel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 1, 5, 1));
        jPanel2.add(jLabel2, java.awt.BorderLayout.PAGE_START);

        jScrollPane2.setBorder(null);

        tblReencauches.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblReencauches.setRowHeight(22);
        jScrollPane2.setViewportView(tblReencauches);

        jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab("HISTORIAL DE REENCAUCHES", jPanel2);

        jPanel4.add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel4, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnVerUbicacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerUbicacionActionPerformed
        // TODO add your handling code here:
        NeumaticosJpaController daoNeumatico = new NeumaticosJpaController(null);
        String categoria = daoNeumatico.findNeumaticos(idNeumatico).getIdCategoria().getNombre();
        if (categoria.equals("Montado")) {
            EntityManagerFactory emf;
            emf = JPAUtil.getEntityManagerFactory();
            EntityManager em = emf.createEntityManager();
            Query q = em.createQuery("SELECT C.idVehiculo FROM DetalleControlCambioNeumatico D"
                    + " JOIN D.idControlCambioNeumatico C"
                    + " WHERE D.idNeumatico.id = :idNeumatico ORDER BY C.id DESC");
            q.setParameter("idNeumatico", idNeumatico);
            q.setMaxResults(1);
            if (!q.getResultList().isEmpty()) {
                Vehiculos tupla = (Vehiculos) q.getSingleResult();
                MontajeDesmontaje montaje = new MontajeDesmontaje(tupla);
                montaje.setIdNeumaticoResaltado(idNeumatico);
                montaje.setSize(Principal.getInstance().getEscritorio().getSize());
                Principal.getInstance().getEscritorio().add(montaje);
                montaje.setVisible(true);
                try {
                    montaje.setMaximum(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                montaje.generarEsquemaMontaje();
                montaje.agregarDescripcionNeumaticos();
            }
        } else {
            JOptionPane.showMessageDialog(this, "Vista no disponible. Neumático no montado en ningún vehículo.");
        }
    }//GEN-LAST:event_btnVerUbicacionActionPerformed

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
        // TODO add your handling code here:
        final DialogoCargando dlgLogin = new DialogoCargando(Principal.getInstance(), true);
        Thread hilo = new Thread() {

            @Override
            public void run() {
                try {
                    ImpresionReportes hojaReporte = new ImpresionReportes(Constantes.REPORTE_HISTORIAL_NEUMATICO);
                    Principal.getInstance().getEscritorio().add(hojaReporte);
                    hojaReporte.setVisible(true);
                    hojaReporte.setMaximum(true);
                    NeumaticosJpaController daoNeumatico = new NeumaticosJpaController(null);
                    hojaReporte.generarReporteHistorialNeumatico(modeloReencuaches, modeloCambios, daoNeumatico.findNeumaticos(idNeumatico));
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                } finally {
                    dlgLogin.dispose();
                }
            }
        };
        hilo.start();
        dlgLogin.setVisible(true);
    }//GEN-LAST:event_btnImprimirActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnVerUbicacion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTable tblCambios;
    private javax.swing.JTable tblReencauches;
    // End of variables declaration//GEN-END:variables
}
